package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {

    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String uri = req.getRequestURI();

        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/**",
                "/wx/notify"
        };

        for (String url : urls) {
            boolean match = antPathMatcher.match(url, uri);
            if (match){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }

        HttpSession session = req.getSession();
        Long userId = (Long) session.getAttribute("employee");

        if (userId != null){
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        Long user1Id = (Long) session.getAttribute("user");

        if (user1Id != null){
            BaseContext.setCurrentId(user1Id);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }


        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }
}
